import _ from 'lodash';
class earth {
  /**
   *
   * @param {*} el 容器标签
   * @param {*} opt cesium配置项
   * @param {*} scene 场景配置json
   */
  constructor(el, opt, scene = '') {
    this.el = el
    this.opt = opt
    this.scene = scene

    this.init()
  }

  destroy() {
    this.earth.destroy()
    this.earth = undefined
    this.scene = undefined
    this.el = undefined
    this.viewer = undefined
    window.earth = undefined
    window.viewer = undefined
  }
  startup() {
    //cesium时钟时间格式化
    function CesiumTimeFormatter(datetime, viewModel) {
      var julianDT = new Cesium.JulianDate()
      Cesium.JulianDate.addHours(datetime, 8, julianDT)
      var gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

      let hour = gregorianDT.hour + ''
      let minute = gregorianDT.minute + ''
      let second = gregorianDT.second + ''
      return `${hour.padStart(2, '0')}:${minute.padStart(
        2,
        '0',
      )}:${second.padStart(2, '0')}`
    }
    //cesium时钟日期格式化
    function CesiumDateFormatter(datetime, viewModel, ignoredate) {
      var julianDT = new Cesium.JulianDate()
      Cesium.JulianDate.addHours(datetime, 8, julianDT)
      var gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

      return `${gregorianDT.year}年${gregorianDT.month}月${gregorianDT.day}日`
    }
    //cesium时间轴格式化
    function CesiumDateTimeFormatter(datetime, viewModel, ignoredate) {
      var julianDT = new Cesium.JulianDate()
      Cesium.JulianDate.addHours(datetime, 8, julianDT)
      var gregorianDT = Cesium.JulianDate.toGregorianDate(julianDT)

      let hour = gregorianDT.hour + ''
      let minute = gregorianDT.minute + ''
      return `${gregorianDT.month}月${gregorianDT.day}日${hour.padStart(
        2,
        '0',
      )}:${minute.padStart(2, '0')}`
    }
    Cesium.Timeline.prototype.makeLabel = CesiumDateTimeFormatter
    //------------------------------------------------------------------

    this.earth = new XE.Earth(this.el, this.opt)
    // this.scene = ''
    if (this.scene == '') {
      this.earth.sceneTree.root = {
        children: [
          {
            czmObject: {
              name: '默认离线影像',
              xbsjType: 'Imagery',
              xbsjImageryProvider: {
                createTileMapServiceImageryProvider: {
                  url:
                    XE.HTML.cesiumDir +
                    'Assets/Textures/NaturalEarthII',
                  fileExtension: 'jpg',
                },
                type: 'createTileMapServiceImageryProvider',
              },
            },
          },
        ],
      }
    } else {

      this.earth.xbsjFromJSON(this.scene)
    }

    this.earth.camera.navigator.showCompass = true
    this.earth.camera.navigator.showDistanceLegend = true
    this.earth.camera.navigator.distanceLegendStyle.bottom = 35
    // console.log(this.earth.camera.navigator);

    window.earth = this.earth
    this.viewer = this.earth.czm.viewer
    window.viewer = this.earth.czm.viewer

    this.viewer.animation.viewModel.dateFormatter = CesiumDateFormatter
    this.viewer.animation.viewModel.timeFormatter = CesiumTimeFormatter
    //隐藏时钟
    setTimeout(() => {
      this.viewer.animation.container.style.visibility = 'hidden'
      this.viewer.timeline.container.style.visibility = 'hidden'
    }, 0)
    //
    // // 添加影像图层
    // const layer = new Cesium.UrlTemplateImageryProvider({
    //     "url": "https://server.arcgisonline.com/arcgis/rest/services/World_Imagery/MapServer/tile/{oz}/{x}/{y}",
    //     customTags: {
    //         oz(imageProvider, x, y, level) {
    //             return level + 1
    //         },
    //     },
    //     tileHeight: 256,
    //     tileWidth: 256,
    //     tilingScheme: new Cesium.GeographicTilingScheme({}),
    // })
    //
    // let img_c = this.earth.sceneTree.$refs.weixing.czmObject
    // img_c.xbsjImageryProvider.UrlTemplateImageryProvider._imageryProvider =
    //     layer
    // img_c.enabled = true

    if (_.has(this.earth.sceneTree.$refs, 'zhuji')) {
      const layer1 = new Cesium.UrlTemplateImageryProvider({
        url: '/tiles/label/{oz}/{x}/{y}',
        customTags: {
          oz(imageProvider, x, y, level) {
            return level + 1
          },
        },
        tileHeight: 256,
        tileWidth: 256,
        tilingScheme: new Cesium.GeographicTilingScheme({}),
      })
  
      let label = this.earth.sceneTree.$refs.zhuji.czmObject
      label.xbsjImageryProvider.UrlTemplateImageryProvider._imageryProvider =
        layer1
    }

    // label.enabled = true
    // window.getViewerReady = this.getViewerReady
  }

  init() {

    if (XE.isReady()) {
      this.startup()
    } else {
      XE.ready()
        .then(() => {
          // 加载标绘插件
          const p1 = XE.HTML.loadJS(
            '/earthsdk/XbsjEarth-Plugins/plottingSymbol/plottingSymbol.js',
          )

          const p2 = XE.HTML.loadJS(
            '/earthsdk/XbsjEarth-Plugins/customPrimitive/customPrimitive.js',
          )

          const p3 = XE.HTML.loadJS(
            '/earthsdk/XbsjEarth-Plugins/customPrimitiveImage/customPrimitiveImage.js',
          )

          const p4 = XE.HTML.loadJS('/earthsdk/scripts/three.min.js') // 部分图元需要加载three.js

          const p5 = XE.HTML.loadJS(
            '/earthsdk/XbsjEarth-Plugins/plottingSymbol2/plottingSymbol2.js',
          )
          return Promise.all([p1, p2, p3, , p4, p5])
        })
        .then(() => {
          this.startup()
        })
    }
  }
  getViewerReady() {
    return new Promise((resolve) => {
      if (!this.viewer) {
        setTimeout(() => {
          resolve(this.getViewerReady())
        }, 30)
      } else {
        resolve(this)
      }
    })
  }
}

export default earth
